<!DOCTYPE html>
<html lang="zn-ch">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>贪吃蛇</title>
<link rel="stylesheet" href="./static/css/bootstrap.min.css">
<style>
body{width:100%;height:100vh;}
.container{width:100%;max-width:900px;margin:0 auto;position: relative;user-select: none;}    
.center{text-align: center;}
.title{padding-bottom:15px;}
.showtable{margin:auto;}
td{text-align: center;font-size:1.5rem;vertical-align: middle!important;color:white;cursor: pointer;}
.show-container{width:100%;padding:0;}
</style>
</head>
<body>
<div class="container">

<div class="row title center">
    <div class="col-xs-12"><h3>贪吃蛇</h3></div>
    <div class="col-xs-12">
        得分：<span class="score">0</span> &nbsp;
        历史最高：<span class="top_score">0</span>&nbsp;
        <button class="btn btn-default start">开始</button>
    </div>
</div>

<div class="row">
    <div class="col-xs-12 center show-container">
        <table class="table-bordered showtable">

        </table>
    </div>
</div>


</div>
</body>
</html>
<script src="./static/js/jquery.min.js"></script>


<script>
var config={
    width:25,
    len:5,
    head:"red",
    body:"green",
    nocolor:"rgba(0, 0, 0, 0)",
    pertime:500,
    data:{
        showheight:0,
        nowlen:5,
        total:0,
        row:0,
        col:0,
        body:[],
        to:"up",//方向
        prev:0,//移动之前的尾巴
        timer:0,
        score:0,
    }
    
};

var fun={
    init:function(){
        config.data.gameover=false;
        config.data.to="up";
        var height=$("body").height();
        var title=$(".title").height();
        config.data.showheight=height-title-15;
        $(".show-container").css({
            height:config.data.showheight,
        })
        this.create_table();
        this.snake();
        var count=Math.floor(config.data.total/10);
        console.log(config.data.total,count)
        this.food(count);
        var _this=this;
        config.data.timer=setInterval(function(){
            _this.change(config.data.to);
        },config.pertime)
        var score=this.cache();
        if(score){
            $(".top_score").text(score);
        }
    },
    rand:function(min,max){
        min-=0.5;
        max+=0.499999999;
       return Math.round(Math.random()*(max-min)+min);
    },
    rand_more:function(min,max,num){
        var re=[];
        while(re.length<num){
            var tem=this.rand(min,max);
            if(this.in_array(tem,re)==false){
                re.push(tem);
            }
        }
        return re;
    },
    in_array:function(item,arr){
       return arr.indexOf(item)!=-1;
    },
    async:function(fn){
        setTimeout(function(){
            fn();
        },0)
    },
    create_table:function(){
        var width=$(".show-container").width();
        var col=Math.floor(width/config.width);
        var left=(width-config.width*col)/2;
        var height=$(".show-container").height();
        var row=Math.floor(height/config.width);
        var str="";
        for(var i=0;i<row;i++){
            str+="<tr>";
                for(var j=0;j<col;j++){
                    str+="<td></td>";
                }
            str+="</tr>";
        }
        $(".showtable").html(str).css({
            left:left,
        });
        $(".showtable td").css({
            width:config.width,
            height:config.width,
        })
        var i=0;
        $(".showtable td").each(function(){
            $(this).attr("index",i);
            i++;
        })
        config.data.total=$(".showtable td").length;
        config.data.row=row;
        config.data.col=col;
        
    },
    snake:function(){
       var arr=[];
       var start=Math.floor((config.data.row-config.len)/2);
       var col=Math.floor(config.data.col/2);
       var index=(start-1)*config.data.col+col-1;
       arr.push(index);
       var body=$(".showtable td");
       body.eq(index).css({
           background:config.head,
       })
       for(var i=0;i<config.len;i++){
            var tem=index+(i+1)*config.data.col;
            arr.push(tem);
            body.eq(tem).css({
                background:config.body,
            })
       }
       config.data.body=arr;  
    },
    move:function(){
        if(config.data.gameover){return false;}
        var body=$(".showtable td");
        var len=config.data.body.length;
        if(config.data.prev!==false){
            body.eq(config.data.prev).css({
                background:config.nocolor,
            })
        }else{
            config.data.score++;
            $(".score").text(config.data.score);
            if((config.data.score-1%100)==0){
                config.pertime-=10;
            }
        }
        config.data.body.forEach(function(i){
            body.eq(i).css({
                background:config.body,
            })
        })
        body.eq(config.data.body[0]).css({
            background:config.head,
        })
        if(config.data.prev===false){
            this.food(1);
        }
    },
    change:function(to){
      var oldarr=config.data.body;
      var oldto=config.data.to;
      var len=oldarr.length;
      var head=oldarr[0];
      config.data.prev=oldarr[len-1];
      var arr=[];
      for(var i=1;i<len;i++){
          arr[i]=oldarr[i-1];
      }
      if(to=="up"){
        config.data.to="up";
        arr[0]=head-config.data.col;
      }else if(to=="left"){
          config.data.to="left";
          arr[0]=head-1;
      }else if(to=="right"){
          config.data.to="right";
          arr[0]=head+1;
      }else if(to=="down"){
          config.data.to="down";
          arr[0]=head+config.data.col;
      }
      if(arr[0]!=oldarr[1]){
            var old=$(".showtable td").eq(arr[0]).css("backgroundColor");
            if(old!=config.nocolor){
                arr.push(config.data.prev);
                config.data.prev=false;
            }
            if(arr[0]%config.data.col==config.data.col-1&&to=="left"){
                this.show_over();
            }else if(arr[0]%config.data.col==0&&to=="right"){
                this.show_over();
            }
            if(this.is_over()){
                this.show_over();
            }
            config.data.body=arr;
            fun.move();
      }else{
          config.data.to=oldto;
      }
    },
    get_empty:function(){
        var re=[];
        var i=0;
        $(".showtable td").each(function(){
            var color=$(this).css("backgroundColor");
            if(color==config.nocolor){
               re.push(i);
            }
            i++;
        })
        return re;
    },
    food:function(num){
        var empty=this.get_empty();
        var color=this.rand_more(0,empty.length-1,num);
        var tds=$(".showtable td");
        color.forEach(function(item){
               tds.eq(item).css({
                   background:"yellow",
               })
        })
    },
    is_over:function(){
        var head=config.data.body[0];
        var len=config.data.body.length;
        if(head<0||head>config.data.total-1){
            return true;
        }
        for(var i=1;i<len;i++){
            if(config.data.body[i]==head){
                return true;
            }
        }
        return false;
    },
    cache:function(score){
        var old=localStorage.getItem("game_max_score");
        if(!score){return old;}
        if(!old||score>old){
            localStorage.setItem("game_max_score",score);
        }
    },
    show_over:function(){
        config.data.gameover=true;
        this.async(function(){
            alert("游戏结束");
        })
        this.cache(config.data.score);
        clearInterval(config.data.timer);
    }

}
fun.init();
$(".start").click(function(){
    fun.init();
})

var controller={
   up:function(){
     fun.change("up");
   },
   left:function(){
     fun.change("left");
   },
   right:function(){
       fun.change("right");
   },
   down:function(){
       fun.change("down");
   }
}


</script>
<script src="./static/js/event.js"></script>